package com.tang.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.tang.sys.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Base64;

@RestController
@RequestMapping("/code")
public class CodeController {
    @Resource
    DefaultKaptcha defaultKaptcha;
    @Autowired
    StringRedisTemplate redisTemplate;
    //生成验证码
    @RequestMapping("/Code")
    public ResponseResult Code() throws IOException {
        // 生成文字验证码
        String text=defaultKaptcha.createText();
        //System.out.println("文字验证码为"+text);
        // 存储验证码到Redis中  并且三分钟到期
        redisTemplate.opsForValue().set("loginCode:Code", text, Duration.ofMinutes(3));
        // 生成图片验证码
        ByteArrayOutputStream out = null;
        BufferedImage image = defaultKaptcha.createImage(text);
        out=new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",out);
        // 对字节组Base64编码
        return ResponseResult.okResult(Base64.getEncoder().encodeToString(out.toByteArray()));
    }
}
